package com.zis.wechat.api.inter.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zis.starter.redis.RedisUtil;
import com.zis.starter.utils.HttpUtil;
import com.zis.starter.utils.MD5Util;
import com.zis.wechat.api.config.WechatAPI;
import com.zis.wechat.api.config.WxConstant;
import com.zis.wechat.api.inter.IEventInter;
import com.zis.wechat.api.inter.IWechatUserInter;
import com.zis.wechat.model.TUser;
import com.zis.wechat.service.ITUserInter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create by wangshen 2018/1/2
 */
@Service
@Transactional("txManager")
public class WechatUserInterImpl implements IWechatUserInter {

    private static final Logger logger = LoggerFactory.getLogger(WechatUserInterImpl.class);

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ITUserInter itUserInter;

    @Autowired
    private IEventInter eventInter;

    //微信用户cache有效时间2小时
    private long LOGIN_INVALID_TIME = 10*60*60L;

    /**
     * 获取用户授权信息
     * @param code
     * @param accountId
     * @return
     */
    @Override
    public String oauthUser(String code, String accountId) {
        String token="";
        try {
            JSONObject account = (JSONObject) redisUtil.getHash(WxConstant.WECHAT_ACCOUNT_KEY, accountId);
            String appSecret = account.getString("");
            String appId = account.getString("");
            String url = WechatAPI.snsOauthAccessTokenUrl(appId, appSecret, code);
            String result =  HttpUtil.httpRequest(url,HttpUtil.METHOD_TYPE_GET,null);
            JSONObject jsonObj = JSON.parseObject(result);
            if(jsonObj.containsKey("errcode")&&!jsonObj.getString("errcode").equals("0")) {
                logger.error(" >>> 获得授权网页临时access_token错误：：" + jsonObj.toJSONString());
            }
            String openId = jsonObj.getString(WxConstant.APPLICATION_OPENID_KEY);
            Map<String, Object> params = new HashMap<>();
            params.put("openId", openId);
            params.put("accountId", accountId);
            token = MD5Util.string2MD5(openId+accountId);
            List<TUser> tUserList = itUserInter.findByCondition(params);
            if(tUserList.size() == 0){
                eventInter.focus(openId,accountId);
            }
            tUserList = itUserInter.findByCondition(params);
            setUserCache(token, tUserList, accountId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 重新设置缓存
     * @param userInfo
     * @return
     */
    @Override
    public String refreshCache(JSONObject userInfo) {
        String token = userInfo.getString("token");
        redisUtil.set(token, userInfo, LOGIN_INVALID_TIME);
        return null;
    }

    /**
     * 设置用户cache
     * @param token
     * @param tUserList
     */
    private void setUserCache(String token, List<TUser> tUserList, String accountId) {
        TUser tUser = tUserList.get(0);
        JSONObject userCache = new JSONObject();
        userCache.put("accountId", accountId);//公众号
        userCache.put("tuId", tUser.getTuId());//微信用户编号
        userCache.put("authState", tUser.getAuthBuss());//认证状态
        userCache.put("token", token);//token
        userCache.put("bussId", "");//业务编号
        userCache.put("nickName", tUser.getNickName());//用户昵称
        userCache.put("headerImg", tUser.getHandimgUrl());//用户头像
        redisUtil.set(token, userCache, LOGIN_INVALID_TIME);
    }

}
